/*
 * Project Name spring-boot-tools
 * File Name DemoController
 * Package Name com.huxiaotu.tools.sse.controller
 * Create Time 2024/7/26
 * Create by name：liujie
 */
package com.huxiaotu.tools.sse.controller;

import com.huxiaosu.tools.common.annotation.ToolsController;
import com.huxiaotu.tools.sse.utils.SseEmitterUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/26 10:37
 */
@Slf4j
@ToolsController("/sse")

public class DemoController {
    @RequestMapping(value="/registerSession",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter getResearchAIAnswer(HttpServletResponse response,String sessionId) {

        response.setContentType("text/event-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", MediaType.TEXT_EVENT_STREAM_VALUE);
        // 设置响应头
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("X-Accel-Buffering", "no");
        SseEmitter emitter = new SseEmitter();
        SseEmitterUtil.eventListener(sessionId,emitter);
        //for(int i =0; i<10;i++){
        //    SseEmitterUtil.sendMsg(sessionId,"hello word "+ DateUtil.now());
        //    log.info("send message ..");
        //}
        //SseEmitterUtil.sendMsg(sessionId,"done");
        //SseEmitterUtil.completed(sessionId);
        return emitter;
    }

    @RequestMapping(value="/getMessage")
    public void getMessage(HttpServletResponse response,String sessionId) {
        for(int i =0; i<10;i++){
            SseEmitterUtil.sendMsg(sessionId,"hello word");
        }
        //SseEmitterUtil.completed(sessionId);

    }
}